import React, { useState, useRef, useEffect } from 'react'
import { LuckyWheel } from '@lucky-canvas/react';
import { Button, Toast, Space, Modal, Avatar, Grid } from "antd-mobile";
import callFeedback from "@/components/common/modalFeedback";
import requewt from "@/utils/requewt";
import { API } from "@/config/api";
import { isValidArr, navigateTo, checkENV2,triggerAppShare } from "@/utils";
import useRecord from "@/components/pages/stores/useRecord";
import { FeedbackComp } from "@/components/pages/wheel";
import { PrizeComp, RuleComp } from "@/components/common";
import Head from "next/head";
import { BASE_PATH } from "@/config";
import GameResult from "@/components/common/modalFeedback/game.result";
import { useToolbar } from '@/components/common/toolbar/hooks';

const pageName = "wheel";
const klassName = pageName.replace(/\./g, '-');

function celebrate() {
  const box = document.getElementById(`box`);

  let count = 200;
  let defaults = {
    zIndex: 9999,
    origin: {
      x: 0.5,
      // since they fall down, start a bit higher than random
      y: .5 || 0
    }
  };

  function fire(particleRatio, opts) {
    confetti(
      Object.assign({}, defaults, opts, {
        particleCount: Math.floor(count * particleRatio)
      })
    );
  }

  fire(0.25, {
    spread: 26,
    startVelocity: 55
  });
  fire(0.2, {
    spread: 60
  });
  fire(0.35, {
    spread: 100,
    decay: 0.91,
    scalar: 0.8
  });
  fire(0.1, {
    spread: 120,
    startVelocity: 25,
    decay: 0.92,
    scalar: 1.2
  });
  fire(0.1, {
    spread: 120,
    startVelocity: 45
  });
}

export default function Wheel(props) {
  const {user} = props;

  const {avatar, nickname} = user?.extra || {};

  const lotterys = useRecord(state => state.lotterys);
  const games = useRecord(state => state.games);
  const update = useRecord(state => state.update);
  const [canShare,setCanshare] = useState(false)

  const myLucky = useRef();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [current, setCurrent] = useState(undefined);
  const [shareBtn, setShareBtn] = useState(true)
const { handleShowPrize } = useToolbar()
  const [blocks] = useState([
    {
      padding: '17px',
      imgs: [{
        src: `${BASE_PATH}/img/wheel/wheel-bg.png`,
        width: '100%',
        height: '100%',
      }]
    }

  ])
  const [prizes, setPrizes] = useState([])
  const [buttons] = useState([
    {
      radius: '65px',
      imgs: [
        {
          src: `${BASE_PATH}/img/wheel/wheel-btn.png`,
          width: '76px',
          height: '90px',
          top: `-54px`
        }
      ],
    }
  ])

  useEffect(() => {
    (async () => {
      await Promise.all([
        await compHandler.fetch(),
        await compHandler.check()
      ])
    })()

    return () => {
      Modal?.clear();
      Toast.clear();
    }
  }, [])

  useEffect(() => {
    if (!isValidArr(prizes)) return
    setTimeout(() => {
      myLucky?.current?.init()
    }, 100)
  }, [prizes])

  const compHandler = {
    // 检测抽奖次数
    check: async () => {
      const resp = await requewt(API.lottery.remain);
      if (resp?.error_code !== 0 || resp?.msg !== `ok`) {
        return
      }
      console.log(resp,'resp')
      update(`lotterys`, resp.data);
      // if (resp.data?.draw_share) {
      //   compHandler.showShare()
      // }
      setCanshare(resp.data?.draw_share)
    },
    showShare: () => {
      const c = callFeedback({
        // bodyClassName: 'result-modal',
        // title: '2',
        closeOnAction:true,
    closeOnMaskClick: false,
        content: <GameResult 
        content={<div className='result-modal'>
          {/* <div className="result-modal-icon">
              <img src={`${BASE_PATH}/img/puzzle/fail_icon.png`} />
              
          </div>
          <div className="result-modal-text">很遗憾，挑战失败</div> */}
          <div className="result-modal-text" style={{marginTop: 30}}>抱歉 你暂无抽奖机会<br/>分享可获得一次抽奖机会</div>
           <Button key="share" className="modal-btn" onClick={async e => {
              const env = await checkENV2();
              if (env === `app`) await triggerAppShare()
              else if (env === `mini`) {
                Toast.show({content: `点击右上角「...」进行分享`})
              } else {
                Toast.show({content: `请在APP或小程序内打开`})
              }

              const resp = await requewt(API.user.share,{body: {source: 'gift'}});
              if (resp?.error_code !== 0) return;
              // setShareBtn(false)
              c.close()
              const m = callFeedback({
        // bodyClassName: 'result-modal',
        // title: '2',
        closeOnAction:true,
    closeOnMaskClick: false,
        content: <GameResult 
        content={<div className='result-modal'>
          {/* <div className="result-modal-icon">
              <img src={`${BASE_PATH}/img/puzzle/fail_icon.png`} />
              
          </div>
          <div className="result-modal-text">很遗憾，挑战失败</div> */}
          <div className="result-modal-text" style={{marginTop: 30}}>抱歉 你暂无抽奖机会<br/>分享可获得一次抽奖机会</div>
          {
             <Button key="share" className="modal-btn" onClick={async e => {
                const resp = await compHandler.check()
                m.close()

              // Toast.show({content: `分享成功`});
              // c.close();
            }}>继续抽奖</Button>
          }
      </div>}
        // actions={[
        //       <Button key="share" className="modal-btn" onClick={async e => {
        //         const env = await checkENV2();
        //         if (env === `app`) await triggerAppShare()
        //         else if (env === `mini`) {
        //           Toast.show({content: `点击右上角「...」进行分享`})
        //         } else {
        //           Toast.show({content: `请在APP或小程序内打开`})
        //         }
  
        //         const resp = await requewt(API.user.share);
        //         if (resp?.error_code !== 0) return;
        //         // Toast.show({content: `分享成功`});
        //         // c.close();
        //       }}>立即分享</Button>
        // ]}
/>,
actions: []
        // (),
        // actions: [
        //     // <Button key="gohome" className="modal-btn" onClick={()=>{
        //     //     c.close()
        //     //     navigateTo('/landing')
        //     // }}>返回首页</Button>,
        //     <Button key="share" className="modal-btn" onClick={async e => {
        //         const env = await checkENV2();
        //         if (env === `app`) await triggerAppShare()
        //         else if (env === `mini`) {
        //           Toast.show({content: `点击右上角「...」进行分享`})
        //         } else {
        //           Toast.show({content: `请在APP或小程序内打开`})
        //         }
  
        //         const resp = await requewt(API.user.share);
        //         if (resp?.error_code !== 0) return;
        //         // Toast.show({content: `分享成功`});
        //         // c.close();
        //       }}>立即分享</Button>
        // ]
    })
              // Toast.show({content: `分享成功`});
              // c.close();
            }}>立即分享</Button> 
      </div>}
        
/>,
actions: []
        // (),
        // actions: [
        //     // <Button key="gohome" className="modal-btn" onClick={()=>{
        //     //     c.close()
        //     //     navigateTo('/landing')
        //     // }}>返回首页</Button>,
        //     <Button key="share" className="modal-btn" onClick={async e => {
        //         const env = await checkENV2();
        //         if (env === `app`) await triggerAppShare()
        //         else if (env === `mini`) {
        //           Toast.show({content: `点击右上角「...」进行分享`})
        //         } else {
        //           Toast.show({content: `请在APP或小程序内打开`})
        //         }
  
        //         const resp = await requewt(API.user.share);
        //         if (resp?.error_code !== 0) return;
        //         // Toast.show({content: `分享成功`});
        //         // c.close();
        //       }}>立即分享</Button>
        // ]
    })
    },
    // 点击按钮开始抽奖
    gamble: async () => {
      
      if (lotterys<=0 &&canShare) {
        return compHandler.showShare()
      }
      if (lotterys <= 0) {
        FeedbackComp({
          item: {
            icon: `${BASE_PATH}/img/prize/prize-7-big.png`,
            category: 99,
            name: '抱歉，<br />您暂无抽奖机会哦！'
          }
        })
        return
      }

      if (loading) return
      Toast.show({content: `请求中`, icon: `loading`})
      setLoading(true);
      const options = {method: `POST`}
      const resp = await requewt(API.lottery.draw, options);
    //   const resp = {
    //     "data": {
    //         "category": 3,
    //         "content": null,
    //         "icon": "/exam1125/img/prize/prize-5-big.png",
    //         "id": 3,
    //         "name": "36U\u5e01",
    //         "today_remain_draw_num": 92
    //     },
    //     "error_code": 0,
    //     "msg": "ok",
    //     "request": "POST /exam1125api/gift/draw"
    // }
      console.log(`gamble.resp`, resp);
      setTimeout(() => {
        setLoading(false)
        Toast.clear();
      }, 300);

      if (resp?.[`error_code`] !== 0 || resp?.[`msg`] !== `ok`) {
        // 特殊的展示方式
        if (resp[`error_code`] === 1001) {
          FeedbackComp({
            item: {
              icon: `https://yinli-qixi-run.varwey.com/2023/3w-ktv-battle-230612/img/price/item-4.png`,
              category: 99,
            }
          })
        } else {
          callFeedback({
            title: <div dangerouslySetInnerHTML={{__html: resp?.msg || `失败!`}}>
            </div>
          })
        }

        return
      }
      const gift = resp.data;
      const index = data.findIndex(e => {
        console.log(e.name,gift.name)
        return e.name === gift.name||e.name === '随机U币'
      });
      // console.log(resp.data)
      // console.log(gift, index)
      if (index < 0) return Toast.show({content: `失败！`})

      setCurrent(resp.data);
      myLucky.current?.play();
      setTimeout(() => {
        myLucky.current?.stop(index)
      }, 1000)
    },
    // 展示中奖结果
    percent: (item) => {
      update(`lotterys`, item.today_remain_draw_num);
      FeedbackComp({item, handler: compHandler})
    },
    // 获取奖品
    fetch: async () => {
      Toast.show({content: `奖品加载中`, icon: `loading`})
      setLoading(true);
      const resp = await requewt(API.prize.entire);
    //   const resp = {
    //     "data": [
    //         {
    //             "content": null,
    //             "icon": "/exam1125/img/prize/prize-1.png",
    //             "id": 10,
    //             "name": "UNI\u5934\u6795\u8170\u9760"
    //         },
    //         {
    //             "content": null,
    //             "icon": "/exam1125/img/prize/prize-2.png",
    //             "id": 11,
    //             "name": "UNI\u591a\u529f\u80fd\u8f66\u8f7d\u5438\u5c18\u5668"
    //         },
    //         {
    //             "content": null,
    //             "icon": "/exam1125/img/prize/prize-3.png",
    //             "id": 12,
    //             "name": "UNI\u591a\u7528\u9014\u6298\u53e0\u7bb1"
    //         },
    //         {
    //             "content": null,
    //             "icon": "/exam1125/img/prize/prize-4.png",
    //             "id": 13,
    //             "name": "UNI\u7bee\u74037\u53f7"
    //         },
    //         {
    //             "content": null,
    //             "icon": "/exam1125/img/prize/prize-5.png",
    //             "id": 14,
    //             "name": "UNI\u7eaa\u5ff5\u62fc\u56fe"
    //         },
    //         {
    //             "content": null,
    //             // "icon": "/exam1125/img/prize/prize-6.png",
    //             "id": 15,
    //             "name": "\u8c22\u8c22\u53c2\u4e0e"
    //         },
    //         {
    //             "content": "",
    //             "icon": "/exam1125/img/prize/prize-6.png",
    //             "id": "100",
    //             "name": "\u968f\u673aU\u5e01"
    //         }
    //     ],
    //     "error_code": 0,
    //     "msg": "ok",
    //     "request": "GET /exam1125api/gift/list"
    // }
      setTimeout(() => {
        setLoading(false);
        Toast.clear();
      }, 800);
      if (resp?.[`error_code`] !== 0 || resp?.[`msg`] !== `ok`) {
        return
      }
      compHandler._filterPrize(resp.data)
      setData(resp.data)
    },
    _filterPrize: prs => {
      if (!isValidArr(prs)) return [];
      let _prizes = [];
      prs.forEach((item, i) => {
        let tmp = {
          _id: item.id,
          background: i === 0 ? `#ffe9e8` : i % 2 === 0 ? `#92b4d9` : `#fff`,
          // background: 'transparent',
          gutter: 2,
          rotate:true,
          fonts: [
            {
              top: '15%',
              text: item.name,
              fontStyle: "Changan Uni",
              fontSize: `14px`,
              lengthLimit: global.innerWidth>375?`75%`:`80%`,
              // wordWrap: false,
              fontColor: `#3a86e4`
            }
          ],
          imgs: [
            {
              src: item.icon ? item.icon : ``,
              width: /prize-2/i.test(item.icon)? '18%':'25%',
              top: '50%'
            }
          ]
        }
        _prizes.push(tmp);
      })
      setPrizes(_prizes)
    },
    // 我的奖品
    
    rule: async () => {
      const m = callFeedback({
        bodyClassName: `rule-modal`,
        title: <>星动战队大作战</>,
        content: <div className="inner"><RuleComp /></div>,
        actions: [],
        closeOnAction: true,
        closeOnMaskClick: false,
      })
    }
  }

  return (
    <>
      <Head>
        <title>转盘抽奖</title>
      </Head>
      <div className={`p-${klassName} page page-thd`}>
        <div className="inner">
          <div className="position-center">
            <div className="award-pool">

              <div className="award-header">
                {/* <div className="title">
                  幸运大转盘
                </div>
                <div>拼图大比拼抽奖池</div> */}
              </div>

              <div className="award-wheel">
                {
                  isValidArr(prizes) &&
                  <LuckyWheel ref={myLucky}
                              id={`test`}
                              width="88vw"
                              height="88vw"
                              blocks={blocks}
                              prizes={prizes}
                              buttons={buttons}
                              onStart={() => compHandler.gamble()}
                              onEnd={prize => { // 抽奖结束会触发end回调
                                compHandler.percent(current)
                                // callFeedback({title: `恭喜你抽到 ${prize.fonts[0].text} 号奖品`})
                              }}
                  />
                }

              </div>

              <div className="award-footer">
                <div className="remain">您还有 <big>{lotterys}</big> 次抽奖机会</div>
              </div>


              <div className="award-ope">
                {/* <Button shape={`rounded`} className="act-btn act-btn-bevel"
                        onClick={async ()=>{
                          const env = await checkENV2();
                          if (env === `app`) await triggerAppShare()
              else if (env === `mini`) {
                Toast.show({content: `点击右上角「...」进行分享`})
              } else {
                Toast.show({content: `请在APP或小程序内打开`})
              }

              const resp = await requewt(API.user.share,{body: {source: 'gift'}});
              setTimeout(() => {
                 compHandler.check()
              }, 2000);
              if (resp?.error_code !== 0) return;
              // setShareBtn(false)
              
                        }}
                >
                  立即分享
                </Button> */}
                <Space className="btn-group mt-3">
                  <Button shape={`rounded`} className="act-btn act-btn-bevel"
                          onClick={handleShowPrize}
                  >
                    我的奖品
                  </Button>

                  <Button shape={`rounded`} className="act-btn act-btn-bevel"
                          onClick={e => navigateTo(`/landing`)}
                  >
                    返回首页
                  </Button>
                </Space>

              </div>
            </div>

          </div>
        </div>

      </div>
    </>
  )
}

Wheel.need2auth = true;
Wheel.pageName = pageName;